package com.fast.security;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.ObjectUtil;
import com.fast.pojo.dto.SecurityUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.security.RrbacManager
 * @description: TODO
 * @since 2024/7/13 下午7:00
 */
@Component
@Slf4j
public class RbacManager {
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * @return [Security] true：认为有权限，false:认为没有权限
     */
    public boolean hasPermission(HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDTO) {
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            if (ObjectUtil.isEmpty(dto.getBackAuthorities())) {
                //没有可用权限
                log.error("访问：{} 权限不匹配", request.getRequestURI());
                return false;
            }
            Set<String> backAuthorities = dto.getBackAuthorities();
            for (String backAuthority : backAuthorities) {
                if (antPathMatcher.match(backAuthority, request.getRequestURI())) {
                    //后端已授权的的权限集合
                    log.info("访问：{} 权限匹配", request.getRequestURI());
                    break;
                }
            }
            return true;
        }
        log.error("访问：{} 权限不匹配", request.getRequestURI());
        return false;
    }
}
